from django.db import models
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
import uuid
from django.urls import reverse
from courses.models import *

class CourseOutline(models.Model):
    """课程大纲模型"""
    course = models.OneToOneField(
        Course,
        on_delete=models.CASCADE,
        verbose_name=_("课程"),
        related_name='outline'
    )
    brief_description = models.TextField(_("大纲简述"), blank=True)
    structure_note = models.TextField(_("结构说明"), blank=True)
    created_at = models.DateTimeField(_("创建时间"), auto_now_add=True)
    updated_at = models.DateTimeField(_("更新时间"), auto_now=True)

    class Meta:
        verbose_name = _("课程大纲")
        verbose_name_plural = _("课程大纲")

    def __str__(self):
        return f"{self.course.title} - 课程大纲"

    def get_absolute_url(self):
        return reverse('course_outline', kwargs={'course_slug': self.course.slug})

    def get_chapter_count(self):
        """获取章节数量"""
        return self.chapters.count()

    def get_lesson_count(self):
        """获取课程中的课时数量"""
        return sum(chapter.lessons.count() for chapter in self.chapters.all())


class Chapter(models.Model):
    """课程章节模型"""
    outline = models.ForeignKey(
        CourseOutline,
        on_delete=models.CASCADE,
        verbose_name=_("课程大纲"),
        related_name='chapters'
    )
    title = models.CharField(_("章节标题"), max_length=100)
    description = models.TextField(_("章节描述"), blank=True)
    order = models.PositiveIntegerField(_("章节顺序"), default=0)
    created_at = models.DateTimeField(_("创建时间"), auto_now_add=True)
    updated_at = models.DateTimeField(_("更新时间"), auto_now=True)

    class Meta:
        verbose_name = _("课程章节")
        verbose_name_plural = _("课程章节")
        unique_together = ['outline', 'order']
        ordering = ['order']

    def __str__(self):
        return f"{self.outline.course.title} - {self.title}"

    def get_absolute_url(self):
        return reverse('chapter_detail', kwargs={
            'course_slug': self.outline.course.slug,
            'chapter_id': self.id
        })

    def get_lesson_count(self):
        """获取章节中的课时数量"""
        return self.lessons.count()

    def is_first_chapter(self):
        """是否为第一章"""
        return self.order == 0


class Lesson(models.Model):
    """课程课时模型"""
    chapter = models.ForeignKey(
        Chapter,
        on_delete=models.CASCADE,
        verbose_name=_("所属章节"),
        related_name='lessons'
    )
    title = models.CharField(_("课时标题"), max_length=100)
    content = models.TextField(_("课时内容"), blank=True)
    video_url = models.URLField(_("视频链接"), blank=True)
    document = models.FileField(_("文档资料"), upload_to='course_documents/', blank=True)
    order = models.PositiveIntegerField(_("课时顺序"), default=0)
    duration = models.IntegerField(_("预计时长（分钟）"), default=10)
    created_at = models.DateTimeField(_("创建时间"), auto_now_add=True)
    updated_at = models.DateTimeField(_("更新时间"), auto_now=True)

    class Meta:
        verbose_name = _("课程课时")
        verbose_name_plural = _("课程课时")
        unique_together = ['chapter', 'order']
        ordering = ['order']

    def __str__(self):
        return f"{self.chapter.outline.course.title} - {self.chapter.title} - {self.title}"

    def get_absolute_url(self):
        return reverse('lesson_detail', kwargs={
            'course_slug': self.chapter.outline.course.slug,
            'chapter_id': self.chapter.id,
            'lesson_id': self.id
        })

    def is_video_available(self):
        """是否有视频资源"""
        return bool(self.video_url)

    def is_document_available(self):
        """是否有文档资源"""
        return bool(self.document)


class ChapterCompletion(models.Model):
    """章节完成记录"""
    student = models.ForeignKey(
        Student,
        on_delete=models.CASCADE,
        verbose_name=_("学生"),
        related_name='chapter_completions'
    )
    chapter = models.ForeignKey(
        Chapter,
        on_delete=models.CASCADE,
        verbose_name=_("章节"),
        related_name='completions'
    )
    completed_at = models.DateTimeField(_("完成时间"), auto_now_add=True)

    class Meta:
        verbose_name = _("章节完成记录")
        verbose_name_plural = _("章节完成记录")
        unique_together = ['student', 'chapter']
        ordering = ['-completed_at']

    def __str__(self):
        return f"{self.student} 完成 {self.chapter}"


class LessonCompletion(models.Model):
    """课时完成记录"""
    student = models.ForeignKey(
        Student,
        on_delete=models.CASCADE,
        verbose_name=_("学生"),
        related_name='lesson_completions'
    )
    lesson = models.ForeignKey(
        Lesson,
        on_delete=models.CASCADE,
        verbose_name=_("课时"),
        related_name='completions'
    )
    completed_at = models.DateTimeField(_("完成时间"), auto_now_add=True)

    class Meta:
        verbose_name = _("课时完成记录")
        verbose_name_plural = _("课时完成记录")
        unique_together = ['student', 'lesson']
        ordering = ['-completed_at']

    def __str__(self):
        return f"{self.student} 完成 {self.lesson}"
